package com.probiz.estore.imports.service.impl;

import java.io.BufferedWriter;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.probiz.estore.imports.handler.ColumnHandler;
import com.probiz.estore.imports.handler.PersistenceHandler;
import com.probiz.estore.imports.model.Column;
import com.probiz.estore.imports.model.ImportMappingConfig;
import com.probiz.estore.imports.model.ImportModel;
import com.probiz.estore.imports.service.ProductImportManager;


public class ProductImportManagerImpl extends BaseImportManagerImpl implements ProductImportManager{
	protected ImportModel doImportTarget(ImportMappingConfig importMappingConfig, List<Column> columns,Integer rowNum,Map<String,String>rowDataMap,BufferedWriter logBw,BufferedWriter failLogBw) throws Exception {
		ImportModel importModel=new ImportModel();
		//日志
		String msg =  "\n第【"+rowNum+"】行 开始执行:"+rowDataMap+"\n";
		logger.info(msg);
		logBw.write(msg);
		
		//导入处理的对象
		Object target=Class.forName(importMappingConfig.getTarget()).newInstance();
		importModel.setTarget(target);
		//默认设置为新增
		importModel.setUpdate(false);
		//===用于标示当然处理深度======
		Integer currLevel =null;

		//导入的数据文件真实的列头
		List<String> realHeaders=importMappingConfig.getRealHeaders();
		try {
			//--------------start:设置要处理对象的值----------------
			nextRow: for (Column column : columns) {
				column.setRowDataMap(rowDataMap);
				column.setRowNum(rowNum);
				for (int i = 0; i < realHeaders.size(); i++) {
					//当配置的列与导入文件列头一致或者是前缀的就处理该数据，
					if (    (realHeaders.get(i).trim().equals(column.getColumnHeader())  || (column.isPrefixAttr() && realHeaders.get(i).trim().startsWith(column.getColumnHeader())) )
							|| column.isInitData()
							|| (StringUtils.isNotEmpty(column.getColumnHeaderSplit())&&ArrayUtils.indexOf(column.getColumnHeader().split(column.getColumnHeaderSplit()), realHeaders.get(i).trim())==0)) {
						if( (null!=currLevel && null== column.getLevel())
							||(null!=currLevel && null!= column.getLevel() && !column.getLevel().equals(currLevel))){
							//如果是深度不一样则不处理,在productNameHandler中改变深度
							continue;
						}
						ColumnHandler handler = column.getHandler();
						//设置当前单元格值
						column.setValue(rowDataMap.get(realHeaders.get(i)),importModel);
						//设置真正列头
						column.setRealHeader(realHeaders.get(i));
						
						
						if (!ImportModel.RESULT_ERROR.equals(importModel.getResult()) && handler!=null) {
							handler.setProperty(importModel,column);
							//===处理当前深度===
							currLevel = importModel.getLevel();
						}
						
						if (column.isInitData()) {
							break;
						}
						
						//出错 则不执行该行
						if (ImportModel.RESULT_ERROR.equals(importModel.getResult())) {
							break nextRow;
						}
					}
				}
			}
			//--------------end:  设置要处理对象的值----------------
		
    		//--------------start:执行持久化方法-------------------
			if (!ImportModel.RESULT_ERROR.equals(importModel.getResult())) {
				PersistenceHandler persistenceHandler=importMappingConfig.getPersistenceHandler();
				//验证
				persistenceHandler.validate(importModel);
				if (!ImportModel.RESULT_ERROR.equals(importModel.getResult())) {
					//执行
					persistenceHandler.saveOrUpdate(importModel);
				}
			}
			
			//日志
			if(ImportModel.RESULT_SUCCESS.equals(importModel.getResult())){
				importInfo.addSuccessCount(importModel.isUpdate());
				
				msg = "成功导入数据。\n";
				logger.info(msg);
				logBw.write(msg);
			}else{
				importInfo.addFailCount(importModel.isUpdate(),rowNum);
				
				logger.info(importModel.getMsg());
				logBw.write(importModel.getMsg()+"\n");
				failLogBw.write("第【"+rowNum+"】行 "+importModel.getMsg()+"\n");
				failLogBw.flush();
			}
			
			msg = "第【"+rowNum+"】行 结束执行\n";
			logger.info(msg);
			logBw.write(msg);
			logBw.flush();
			
			//--------------end:  执行持久化方法-------------------
			
		} catch (Exception e) {
			importModel.setResult(ImportModel.RESULT_ERROR);
			msg = "错误信息："+e+"\n";
			logger.warn(msg);
			logBw.write(msg);
			failLogBw.write("第【"+rowNum+"】行 "+msg+"\n");
		}
		//===处理当前深度===
		currLevel =null;
		return importModel;
		
	}
}
